<template>
  <div class="main-container">
    <div class="header flex-c">
      <div class="header-wrap flex-b-c">
        <div class="header-left flex-b-c">
          <div class="logo flex-c">
            <img src="../assets/images/pic_logo_200x60.png">
          </div>
          <div class="tab">
            <div v-for="(item, i) in tabList" :key="i" :class="{'active': item.active}" @click="chooseTab(item)">
              <span>{{ item.name }}</span>
              <span v-show="item.active" class="active-line"></span>
            </div>
          </div>
        </div>
        <div class="header-right flex-b-c">
          <div class="header-input flex-c">
            <img src="../assets/images/icon_shousuo_24.png" class="can-click" @click="search">
            <el-input class="flex-c" v-model="courseTitle" @keyup.enter.native="search" size="small" placeholder="搜索课程或讲师"></el-input>
          </div>
          <el-dropdown v-if="userName" @command="logOut">
            <div class="message-user flex-c can-click">
              <span>{{ userName }}</span>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div v-else class="message-user flex-c can-click" @click="toLogin()">
            <span>{{ userName ? userName : '登录' }}</span>
          </div>
        </div>
      </div>
    </div>
    <router-view class="router-view" />
  </div>
</template>

<script>
  import { REG, TEXT_MESSAGE } from '@/utils/verification'
  import { publicKey } from '@/utils'
  import { JSEncrypt } from 'jsencrypt'
export default {
  name: 'index',
  computed: {
    tabList(){
      if(sessionStorage.userId){
        let routeName = this.$route.name;
        if(routeName === 'index'){
          return [
            { name: '全部课程', active: true, url: '/index' },
            { name: '我的课程', active: false, url: '/myCourse' }
          ]
        }else {
          return [
            { name: '全部课程', active: false, url: '/index' },
            { name: '我的课程', active: true, url: '/myCourse' }
          ]
        }
      }else {
        return [
          { name: '全部课程', active: true, url: '/index' },
        ]
      }
    },
  },
  data () {
    /* 验证确认密码和第一次密码相同 */
    let checkConfirmPwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error('请再次输入登录密码!'))
      }else if (value !== this.pswForm.newPsw) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    };
    return {
      messageUnReadCount: 0,
      courseTitle: '',
      headerActive: false,
      textColor: 'rgba(255, 255, 255, 0.5)',
      activeTextColor: '#ffffff',
      userName: '',
      ifIndex: false,
      isMobile: false,
      bottomTabList: [
        {
          name: '课程',
          svg: 'home',
          // active: true,
          url: '/index'
        },
        {
          name: '我的',
          svg: 'my',
          // active: false,
          url: '/app/my'
        },
      ],
      editInfoDialog: false, // 修改信息弹窗
      infoForm: {
        infoName: ''
      }, // 用户信息
      infoName: '',
      oldPsw: '',
      newPsw: '',
      repeatNewPsw: '',
      editPswDialog: false,
      pswForm: {
        oldPsw: '',
        newPsw: '',
        repeatNewPsw: '',
      },
    };
  },
  watch: {
    headerActive(val){
      if(val){
        this.textColor = '#adadad';
        this.activeTextColor = '#333333'
      }else {
        this.textColor = 'rgba(255, 255, 255, 0.5)';
        this.activeTextColor = '#ffffff'
      }
    },
    '$route': 'getPath'
  },
  created () {
    if(sessionStorage.userName){
      this.userName = sessionStorage.userName
    }
    if(this.Common.isMobile()){
      this.isMobile = true;
    }else {
      this.isMobile = false;
    }
    if(sessionStorage.userNameCopy) this.userName = sessionStorage.userNameCopy;
  },
  mounted(){
    window.addEventListener('scroll', this.handleScroll, true) // 监听滚动事件
    // this.getPath();
    // this.getMessageUnReadCount();
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    /**
     * 选择菜单
     **/
    selectMenu(){
      this.courseTitle = '';
    },
    /**
     * 打开修改用户名弹窗
     **/
    editInfo(){
      this.editInfoDialog = true;
      this.infoForm.infoName = this.userName;
    },
    /**
     * 打开修改密码弹窗
     **/
    editPsw(){
      this.editPswDialog = true;
    },
    /**
     * 修改密码
     **/
    commitPsw(){
      let form = this.$refs.ruleForm;
      form.validate((valid) => {
        if (valid) {
          const { oldPsw, newPsw } = this.pswForm;
          const key = publicKey();
          const encryptor = new JSEncrypt();
          encryptor.setPublicKey(key);
          const oldencrypted = encryptor.encrypt(oldPsw);
          const newencrypted = encryptor.encrypt(newPsw);
          this.Request.updateUserPassword({
            params: {
              id: sessionStorage.userId,
              oldPassword: oldencrypted,
              newPassword: newencrypted
            },
            success: (data, res)=>{
              if(res.status.code === 200){
                this.$message.success('密码修改成功');
                this.editPswDialog = false;
              }
            }
          });
        }
      })
    },
    /**
     * 修改密码弹窗-关闭回调
     **/
    closeEditPswDialog(){
      this.pswForm.oldPsw = '';
      this.pswForm.newPsw = '';
      this.pswForm.repeatNewPsw = '';
      this.$refs.ruleForm.resetFields();
    },
    /**
     * 修改用户名
     **/
    commitInfoName(){
      let form = this.$refs.infoNameForm;
      form.validate(async (valid) => {
        if (valid) {
          this.Request.updateUserName({
            params: {
              id: sessionStorage.userId,
              userName: this.infoForm.infoName
            },
            success: (data, res)=>{
              if(res.status.code === 200){
                sessionStorage.userNameCopy = this.infoForm.infoName;
                this.userName = this.infoForm.infoName;
                this.Common.changeURLStatic('userName', escape(this.infoForm.infoName)); // 修改地址栏userName值
                this.$message.success('用户名修改成功');
                this.editInfoDialog = false;
              }
            }
          });
        }
      });
    },
    /**
    * 获取路由
    **/
    getPath(){
      if(this.$route.path !== '/index'){
        this.ifIndex = true;
        this.headerActive = true
      }else {
        this.ifIndex = false;
        this.headerActive = false
      }
    },
    handleScroll (e) {
      let scrollTop = this.$parent.$el.scrollTop; // 表示获取router-view上一级的scrollTop
      if (scrollTop > 0) {
        this.headerActive = true;
      }else {
        if(this.ifIndex){
          this.headerActive = true
        }else {
          this.headerActive = false
        }
      }
    },
    search () {
      if(!this.courseTitle){
        this.$message.warning('请输入关键字');
        return
      }
      this.$router.push({
        path: '/searchList',
        query: {
          courseTitle: this.courseTitle
        }
      })
    },
    /**
    * 登出
    **/
    logOut(){
      this.Common.delCookie('accountDataInfo')
      sessionStorage.clear();
      this.$router.replace('/login')
    },
    /**
     * tab
     **/
    chooseTab(item){
      for(let item of this.tabList){
        item.active = false
      }
      this.$router.push({
        path: item.url
      });
      item.active = true
    },
    getMessageUnReadCount(){
      const params = {userId: sessionStorage.userId}
      this.Request.getDrillMessageUnRead({params: params}).then((res) => {
        this.messageUnReadCount = (res && res.data) || 0;
      });
    },
    toMessage(){
      this.$router.push({
        name: 'message',
      })
    },
    toLogin(){
      this.$router.replace({
        path: '/login'
      })
    },
  }
};
</script>
<style scoped lang="scss">
  .main-container{
    width: 100%;
    cursor: unset;
    position: absolute;
    height: 100%;
    .header{
      height: 0.6rem;
      display: flex;
      align-items: center;
      position: sticky;
      top: 0;
      border-bottom: 2px solid #f5f5fa;
      padding: 0 0.133rem;
      .header-wrap{
        height: 100%;
        width: calc(100% - 0.266rem);
        .header-left{
          .logo{
            margin-right: 0.333rem;
            img{
              height: 0.4rem;
              margin-right: 0.133rem;
            }
          }
          .tab{
            display: flex;
            >div{
              width: 0.633rem;
              height: 0.26rem;
              line-height: 0.26rem;
              cursor: pointer;
              font-size: 0.113rem;
              position: relative;
              text-align: center;
              .active-line{
                position: absolute;
                left: 0.316rem;
                margin-left: -10px;
                height: 100%;
                width: 0.133rem;
                border-bottom: 2px solid #4D6DF4;
              }
            }
            div.active{
              color: #4D6DF4;
            }
          }
        }
        .header-right{
          .header-input{
            margin-right: 0.266rem;
            width: 2.666rem;
            height: 0.266rem;
            background: #F5F5FA;
            border-radius: 0.333rem;
            padding: 0 0.133rem;
            .el-input{
              /deep/ .el-input__inner{
                border: none;
                background: #F5F5FA;
              }
            }
          }
          .message-user{
            padding: 0.067rem 0.133rem;
            background: #4D6DF4;
            border-radius: 0.333rem;
            span{
              color: #fff;
              font-size: 0.093rem;
            }
          }
        }
      }
    }
    .router-view{
      height: calc(100% - 0.6rem);
      background-color: #f5f5fa;
    }
  }
</style>
